package com.iss.wyy.helper;

import com.iss.wyy.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BeanHelper {
    /**
     * 定义类集合（用于存放bean类与bean实例的映射关系）
     */
    private static final Map<Class<?>,Object> BEAN_MAP = new HashMap<>();
    private static  Map<Class<?>,Object> CONTROLLER_BEAN_MAP = new HashMap<>();
    private static  Map<Class<?>,Object> REPOSITORY_BEAN_MAP = new HashMap<>();
    private static  Map<Class<?>,Object> SERVICE_BEAN_MAP = new HashMap<>();

    /**
     * 初始化所有bean
     */
    static {
        Set<Class<?>> annotationClassSet = ClassHelper.getAnnotationClassSet();
        for (Class<?> cls: annotationClassSet) {
            BEAN_MAP.put(cls,ReflectionUtil.newInstance(cls));
        }
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        for (Class<?> cls: controllerClassSet) {
            CONTROLLER_BEAN_MAP.put(cls,ReflectionUtil.newInstance(cls));
        }
        Set<Class<?>> repositoryClassSet = ClassHelper.getRepositoryClassSet();
        for (Class<?> cls: repositoryClassSet) {
            REPOSITORY_BEAN_MAP.put(cls,ReflectionUtil.newInstance(cls));
        }
        Set<Class<?>> serviceClassSet = ClassHelper.getServiceClassSet();
        for (Class<?> cls: serviceClassSet) {
            SERVICE_BEAN_MAP.put(cls,ReflectionUtil.newInstance(cls));
        }


    }

    /**
     * 获取所有有注解的bean映射
     */
    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }
    /**
     * 获取所有Controller的bean映射
     */
    public static Map<Class<?>, Object> getControllerBeanMap() {
        return CONTROLLER_BEAN_MAP;
    }
    /**
     * 获取所有Repository的bean映射
     */
    public static Map<Class<?>, Object> getRepositoryBeanMap() {
        return REPOSITORY_BEAN_MAP;
    }
    /**
     * 获取所有Service的bean映射
     */
    public static Map<Class<?>, Object> getServiceBeanMap() {
        return SERVICE_BEAN_MAP;
    }

    /**
     * 获取某个特定bean实例
     */
    public static <T> T getBean(Class<T> cls){
        if(!BEAN_MAP.containsKey(cls)){
            throw new RuntimeException("can not get bean by class:"+cls);
        }
        return (T) BEAN_MAP.get(cls);
    }
    /**
     * 设置某个特定bean实例
     */
    public static void setBean(Class<?> cls,Object obj){
        BEAN_MAP.put(cls,obj);
    }
}
